#!/usr/bin/env python
# -*- coding: utf-8 -*-
####
# Virgin Mobile Broadband2Go Connection Manager 0.12
####
# Requires PyGtk 2.0 or greater, xterm, usb_modeswitch, and gnome-ppp
# Please setup your path to your usb_modeswitch compiled binary
# as an example, I used mine, with is under my ~/src folder.
# This frontend is GPL opensource.
#
# coded by Adam "RabidWeezle" Smith: rabidweezle@gmail.com
###
import subprocess
import sys

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade

######
## app paths, change these if you need to
######
##usb modeswitch using xterm so you can see output if it errors. Changed in 0.11 to reflect a more sane installer.
#This shouldn't have to be changed... works in kubuntu and ubuntu jaunty
driver = "gksu modprobe usbserial vendor=0x1410 product=0x6002"
#This is the only method I know of that works
dialer = "gksu gnome-ppp"

def run_it(x):
  """ makes a basic subprocess that requires shell. Only use when shell is absolutely needed... 
      ex: run_it("lsusb|grep Novatel)"""
  subprocess.Popen(x, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=True, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0)

def notify(title, message):
  """Sends a notification message for the user on the
      notification tab, ex: notify(Warning, Battery level at critical
      level
  """
  try:
    import pynotify
    if pynotify.init("VMDialer"):
      n = pynotify.Notification(title, message)
      n.show()
    else:
      print "there was a problem initializing the pynotify module"
  except:
      print "you don't seem to have pynotify installed"

def dev_detect():
  """dev_detect()
      Basically, this detects the status of the Novatel 760
      and sends a notification to the user. There are no
      arguments to pass to it.
  """
  print '\nDetecting USB760'
  g = subprocess.Popen("lsusb|grep Novatel", shell=True, stdout=subprocess.PIPE)
  stdout_value = g.communicate()[0]
  mode = (stdout_value[28])
  result = int(mode)
  if result == 6:
    notify('Success!', 'Your device is in modem mode')
    return 
  elif result == 5:
    notify('Failure', 'retrying...')
    dev_detect()
  else:
    notify('Error', 'Did you plug it in?')
    return

class VirginMobileGTK:
	"""This is an application to load the Broadband2GO
	device driver and start the dialer
	"""

	def __init__(self):
		
		#Set the Glade file
		self.gladefile = "virginmobile.glade"  
	        self.wTree = gtk.glade.XML(self.gladefile) 

		#Create our dictionary and connect it
		dic = { "on_button2_clicked" : self.button2_clicked, 
			"on_button1_clicked" : self.button1_clicked, 
			"on_window1_destroy" : gtk.main_quit }
		self.wTree.signal_autoconnect(dic)


## These next 2 lines say what to do when the "switch to modem" button is clicked, change this to reflect your usb_modeswitch path
	def button1_clicked(self, widget):
		subprocess.call(["xterm", "-e", "sudo", "/usr/share/vmdialer/usb_modeswitch"]) ## used call() so it will wait before testing. Removed usbms variable because this is more sane.
		dev_detect()
	
	def button2_clicked(self, widget):
		foo = driver+" && "+dialer
		run_it(foo)
	
	  #Get the Main Window, and connect the "destroy" event
		self.window = self.wTree.get_widget("window1")
		if (self.window):
		  self.window.connect("destroy", gtk.main_quit)


if __name__ == "__main__":
	VMGTK = VirginMobileGTK()
	gtk.main()